package cn.wolfcode.p2p.base.shiro;

import cn.wolfcode.p2p.base.util.JSONResult;
import cn.wolfcode.p2p.base.util.LoginInfoContext;
import com.alibaba.fastjson.JSON;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;

public class ExtendsFormAuthenticationFilter extends FormAuthenticationFilter {

    // 覆写登录成功的方法
    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        // 设置响应格式
        response.setContentType("text/json;charset=utf-8");



        // 响应json格式的JSONResult
        response.getWriter().write(JSON.toJSONString(new JSONResult()));
        // 不放行
        return false;
    }
    // 覆写登录失败的方法
    @Override
    protected boolean onLoginFailure(AuthenticationToken token, AuthenticationException e, ServletRequest request, ServletResponse response) {
        // 设置响应格式
        response.setContentType("text/json;charset=utf-8");
        // 登录失败清空session
        LoginInfoContext.setCurrentLoginInfo(null);

        JSONResult result = new JSONResult();
        e.printStackTrace();
        // 判断异常信息
        if (e instanceof UnknownAccountException){
            result.mark("用户名不存在");
        } else if (e instanceof IncorrectCredentialsException){
            result.mark("密码错误");
        }
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        // 不放行
        return false;

    }
}
